package com.csun.nusing.ui;

import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import com.baidu.tts.client.SpeechSynthesizer;
import com.csun.nusing.App;
import com.csun.nusing.presenter.BasePresenter;
import com.csun.nusing.util.SPUtils;

/**
 * 基于mvp架构使用的一个BaseActivity类 继承的Activity在getContentViewId()方法中设置布局
 * 在initSubViews方法中findView初始化 在initdata方法中使用Presenter操作数据 ClassName:
 * BaseActivity
 * 
 * @Description: 被继承
 * @author fzq
 * @date 2017-10-18
 */
public abstract class BaseActivity<T extends BasePresenter> extends
		FragmentActivity implements IView {

	protected T mPresenter;
	protected App app;
	private Float scale;// 0.85 小, 1 标准大小, 1.15 大，1.3 超大 ，1.45 特大
	protected SpeechSynthesizer mSpeechSynthesizer;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		View containerView = getLayoutInflater().inflate(getContentViewId(),
				getViewGroupRoot());
		setContentView(containerView);
		initPresenter();
		app = App.getInstance();
		initSubViews(containerView);
		initData();
		initFontScale();
		mSpeechSynthesizer = App.getTTFspeake(this);
	}
	//0.8  //1.25
	// 0.8 小, 1 标准大小, 1.25 大
	private void initFontScale() {
		scale = (Float) SPUtils.get(this, "SCALE", (float)1.0);
		Configuration configuration = getResources().getConfiguration();
		configuration.fontScale = scale;
		// 0.8 小, 1 标准大小, 1.25 大
		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		metrics.scaledDensity = configuration.fontScale * metrics.density;
		getBaseContext().getResources().updateConfiguration(configuration,
				metrics);
	}

	private void initPresenter() {
		mPresenter = getPresenter();
	}

	protected T getPresenter() {
		return null;
	}

	@Override
	public abstract int getContentViewId();

	@Override
	public ViewGroup getViewGroupRoot() {
		return null;
	}

	@Override
	public void initSubViews(View view) {
	}

	@Override
	public void initData() {
	}

	/**
	 * 对back键的点击做判断，如果按back键，默认退回到主页面
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	// 监听返回键
	public void OnBACK(View view) {
		finish();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mPresenter != null)
			mPresenter.detachViewRef();
	}

}
